<template>
  <div class="form">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" size="small" @click="newShow">新增</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="articleList"
        border
        style="width: 100%"
      >
        <el-table-column
          fixed
          label="序号"
          type="index"
          align="center"
          width="80"
        />
        <el-table-column
          show-overflow-tooltip
          label="品牌名称"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <p>{{ scope.row.name }}</p>
          </template>
        </el-table-column>
        <el-table-column
          label="展示状态"
          align="center"
          width="200"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.showStatus"
              inactive-text="是否展示"
              :active-value="1"
              :inactive-value="0"
              @change="changeNew(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="Logo"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            <img :src="scope.row.logo" style="width:100px; height:120px">
          </template>
        </el-table-column>
        <el-table-column
          label="专区大图"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            <img :src="scope.row.bigPic" style="width:100px; height:120px">
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          align="center"
          width="240"
        />
        <el-table-column
          prop="sort"
          align="center"
          label="排序"
          width="100"
        />
        <el-table-column
          prop="productCommentCount"
          align="center"
          label="产品评论数量"
          width="130"
        />
        <el-table-column
          prop="productCount"
          label="产品数量"
          align="center"
          width="120"
        />
        <el-table-column
          prop="sort"
          label="是否品牌制造商"
          align="center"
          width="120"
        > <template slot-scope="scope">
          <p v-if="scope.row.factoryStatus == 1">是</p>
          <p v-else>不是</p>
        </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="doDel(scope.row.id)">删除</el-button>
            <el-button type="success" size="mini" @click="goEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top:20px; text-align:right"
        :current-page="articleObj.start"
        :page-sizes="articleObj.sizes"
        :page-size="articleObj.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="articleObj.totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      title="品牌详情"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-form ref="forms" :model="brand" :rules="rules" label-width="80px" :inline="false" size="normal">
        <el-row :gutter="30">
          <el-col :span="12" :offset="0">
            <el-form-item label="品牌名称" prop="name">
              <el-input v-model="brand.name" placeholder="品牌名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="首字母">
              <el-input v-model="brand.firstLetter" placeholder="首字母" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="brand.sort" placeholder="排序" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="产品数量" prop="productCount">
              <el-input v-model="brand.productCount" placeholder="产品数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="是否展示">
              <el-switch
                v-model="brand.showStatus "
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="是否为品牌制造商" label-width="120">
              <el-switch
                v-model="brand.factoryStatus "
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <h4>上传专区大图</h4>
            <el-upload
              class="avatar-uploader"
              action="/lejuAdmin/material/uploadFileOss"
              :headers="{ token }"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="brand.bigPic" :src="brand.bigPic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-col>
          <el-col :span="12" :offset="0">
            <h4>上传Logo</h4>
            <el-upload
              class="avatar-uploader"
              action="/lejuAdmin/material/uploadFileOss"
              :headers="{ token }"
              :on-success="handleAvatarLogo"
              :show-file-list="false"
            >
              <img v-if="brand.logo" :src="brand.logo" class="avatar">
              <span v-if="brand.logo" @click.stop="delImg">删除logo</span>
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="newAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import mixin from '@/mixins'
import { getToken } from '@/utils/myAuth'
import {
  delBrand as deletes,
  switchShowStatus,
  findBrandByPage,
  addBrand,
  updateBrand } from '@/api/commdity/brand'
export default {
  // mixins: [mixin],
  data() {
    var checkAge = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        return callback(new Error('排序不能为空'))
      }
      setTimeout(() => {
        var rag = /^\+?[1-9][0-9]*$/
        if (!rag.test(Number(value))) {
          callback(new Error('排序必须为正整数'))
        } else {
          callback()
        }
      }, 1000)
    }
    var checkNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('产品数量不能为空'))
      }
      setTimeout(() => {
        var rag = /^\+?[1-9][0-9]*$/
        // console.log(Number(value), rag.test(Number(value)))
        if (!rag.test(Number(value))) {
          callback(new Error('产品数量必须为正整数'))
        } else {
          if (value > 1000) {
            callback(new Error('产品数量不能大于1000'))
          } else {
            callback()
          }
        }
      }, 500)
    }
    return {
      // imageUrl:'',
      searchForm: {},
      judgeShow: false,
      value: '',
      loading: false,
      articleObj: {
        limit: 5,
        start: 1,
        totalCount: 0,
        sizes: [5, 10, 15, 20]
      },
      articleList: [],
      dialogVisible: false,
      brand: {
        name: '', // 品牌名称
        showStatus: 0, // 是否展示
        factoryStatus: 0, // 是否为品牌制造商
        firstLetter: '', // 首字母
        bigPic: '', // 专区大图
        productCount: '', // 产品数量
        logo: '', // 品牌logo图
        sort: '' // 排序
      },
      rules: {
        name: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, validator: checkAge, trigger: 'blur' }
        ],
        productCount: [
          { required: true, validator: checkNum, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    token() {
      return getToken()
    }
  },
  created() {
    this.init()
  },
  mounted() {

  },
  methods: {
    handleAvatarSuccess(res, file) {
      const { success, data, message: errMag } = res
      if (success) {
        const { fileUrl } = data
        this.$message.success('上传成功')
        this.brand.bigPic = fileUrl
        console.log(this.brand.bigPic)
      } else {
        this.$message.error(errMag)
      }
    },
    handleAvatarLogo(res, file) {
      const { success, data, message: errMag } = res
      if (success) {
        const { fileUrl } = data
        this.$message.success('上传成功')
        this.brand.logo = fileUrl
        console.log(this.brand.logo)
      } else {
        this.$message.error(errMag)
      }
    },
    beforeAvatarUpload(file) {
      var rag = /image\/(jpg|png|jpeg)/g
      const img = rag.test(file.type)
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 1.5

      if (!img) {
        this.$message.error('上传头像只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!')
      }
      // return isLt2M
      return img && isLt2M
    },
    delImg() { // 删除上传的图片
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.brand.logo = ''
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
      })
    },
    onReset() { // 重置
      this.searchForm = {}
      this.init()
    },
    newShow() { // 点击新增打开遮罩层
      this.judgeShow = false
      this.brand = {
        name: '', // 品牌名称
        showStatus: 0, // 是否展示
        factoryStatus: 0, // 是否为品牌制造商
        firstLetter: '', // 首字母
        bigPic: '', // 专区大图
        productCount: '', // 产品数量
        logo: '', // 品牌logo图
        sort: '' // 排序
      }
      this.dialogVisible = true
    },
    goEdit(params) { // 点击编辑打开遮罩层
      this.judgeShow = true
      this.brand = params
      this.dialogVisible = true
    },
    cancel() { // 遮罩层点击取消
      if (this.judgeShow) {
        this.dialogVisible = false
      } else {
        this.dialogVisible = false
        this.brand.logo = ''
        this.brand.bigPic = ''
        this.$refs.forms.resetFields()
      }
    },

    newAdd() { // 保存
      this.$refs.forms.validate((valid) => {
        if (valid) {
          if (this.brand.id !== undefined) {
            this.$confirm('是否确认修改品牌', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'info'
            }).then(() => {
              updateBrand(this.brand).then(res => {
                const { message: errmag, success } = res
                if (success) {
                  this.$message.success('编辑成功')
                  this.dialogVisible = false
                  this.brand = {}
                  this.init()
                } else {
                  this.$message.error(errmag)
                }
              })
            }).catch(() => {
            })
          } else {
            addBrand(this.brand).then(res => {
              const { message: errmag, success } = res
              if (success) {
                this.$message.success('新增成功')
                this.dialogVisible = false
                this.brand = {}
                this.init()
              } else {
                this.$message.error(errmag)
              }
            })
          }
        } else {
          this.$message.error('请注意表单验证')
          return false
        }
      })
    },
    changeNew(params) { // 更新
      switchShowStatus({
        id: params.id,
        status: params.showStatus
      }).then(res => {
        const { message: errMag, success } = res
        if (success) {
          this.$message.success('更新状态成功')
        } else {
          this.$message.error(errMag)
        }
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    init() {
      this.loading = true
      const { start, limit } = this.articleObj
      findBrandByPage(start, limit).then(
        res => {
          const { success, data, message: errMge } = res
          if (success) {
            const { rows, total } = data
            this.articleList = rows
            console.log(this.articleList)
            this.articleObj.totalCount = total
          } else {
            this.$message.error(errMge)
          }
          this.loading = false
        }
      )
    },

    handleSizeChange(val) {
    // console.log(`每页 ${val} 条`)
      this.articleObj.limit = val
      this.init()
    },
    handleCurrentChange(val) {
    // console.log(`当前页: ${val}`)
      this.articleObj.start = val
      this.init()
    },
    doDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletes(id).then(res => {
          this.init()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
      })
    }

  }
}

</script>

<style scoped lang="scss">
    .form{
        background-color: #f0f2f5;
        padding-top: 30px;
        .el-collapse{
            padding: 10px;
            background-color: #fff;
        }
        .el-collapse1{
            margin: 30px;
            padding: 10px;
        }
        .box-card{
            margin:0px 30px;
        }
         .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
    }
</style>
